package com.client;

import com.config.Config;
import com.handle.DefaultHandle;
import com.handle.IdleStateEventHandle;
import com.protocol.MessageCodecSharable;
import com.protocol.ProtocolFrameDecoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author linyu.dai
 * @project rpc
 * @description
 * @creat 2022/11/27 10:41:50
 */
@Slf4j
public class RegisterClient {

    private static final String HOST = Config.get("rpc.register.host");
    private static final Integer PORT = Integer.valueOf(Config.get("rpc.register.port"));

    public static void run(){
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            Channel channel = new Bootstrap()
                    .group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new ProtocolFrameDecoder());
                            ch.pipeline().addLast(new MessageCodecSharable());
                            ch.pipeline().addLast(new DefaultHandle());
                            ch.pipeline().addLast(new IdleStateHandler(0,3,0));
                            ch.pipeline().addLast(new IdleStateEventHandle());
                        }
                    }).connect(HOST, PORT).sync().channel();
            log.info("connect register success:{},{}",HOST,PORT);

            //监听channel关闭
            channel.closeFuture().addListener(future -> {
                //关闭group线程池 彻底关闭client
                group.shutdownGracefully();
            });

        }catch (Exception e){
            log.error("register client start error {}",e.getMessage());
        }
    }
}
